package algorithm.binarysearch;

// 二分查找的非递归实现
public class BinarySearchDemo {


    public static void main(String[] args) {
        int[] dataArray1 =
                {2, 3, 3, 6, 6, 6, 7, 9, 9, 9, 10, 10, 13, 15, 15, 16, 16, 18, 19, 20};

        System.out.println(binarySearch(dataArray1, 2));

    }

    private static int binarySearch(int[] dataArray, int target) {
        if (dataArray == null) {
            return -1;
        }
        int left = 0;
        int right = dataArray.length - 1;

        while (left <= right) {
            int mid = (left + right) / 2;
            // 相等直接返回
            if (dataArray[mid] == target) {
                return mid;
            }
            // target比较小 则取前半部分
            if (dataArray[mid] > target) {
                right = mid;
                continue;
            }
            // target比较大 则取后半部分
            if (dataArray[mid] < target) {
                left = mid + 1;
            }
        }

        return -1;
    }
}
